package com.peanut.youfupay.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;


public class AESUtil {

	/**
	 * 密钥算法
	 */
	private static final String ALGORITHM = "AES";
	/**
	 * 加解密算法/工作模式/填充方式
	 */
	private static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS5Padding";

	/**
	 * AES加密
	 * @param data
	 * @param key 任意长度
	 * @return
	 * @throws Exception
	 */
	public static String encryptData(String data,String key) throws Exception {
		// 创建密码器
		Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
		SecretKeySpec secretKey = new SecretKeySpec(Md5Encrypt.md5(key, "UTF-8").toLowerCase().getBytes(), ALGORITHM);
		// 初始化
		cipher.init(Cipher.ENCRYPT_MODE, secretKey);
		return BASE64Util.encryptBASE64(cipher.doFinal(data.getBytes()));
	}

	/**
	 * AES解密
	 * @param base64Data
	 * @param key 秘钥 任意长度
	 * @return
	 * @throws Exception
	 */

	public static String decryptData(String base64Data,String key) throws Exception {
//		Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
		// 创建密码器
		Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
		SecretKeySpec secretKey = new SecretKeySpec(Md5Encrypt.md5(key, "UTF-8").toLowerCase().getBytes(), ALGORITHM);
		// 初始化
		cipher.init(Cipher.DECRYPT_MODE, secretKey);
		return new String(cipher.doFinal(BASE64Util.decryptBASE64(base64Data)));
	}

	public static void main(String[] args) throws Exception {
		//String A 为测试字符串，是微信返回过来的退款通知字符串
		//key:AES对称密钥  商户生成
		String key="DA17CC11D9A03FBC87A788036D260DFF";
		//加密前字符串
		String A = "为测试字符串，是微信返回过来的退款通知字符串";
		//加密后字符串
		String B = AESUtil.encryptData(A,key);
		System.out.println(B);
		//解密得到的字符串
		String C=AESUtil.decryptData(B,key);
		System.out.println(C);
	}

}
